/* Copyright (c) 2008-2010 -- CommonsWare, LLC
 * Modified by Aris Priyantoro

	 Licensed under the Apache License, Version 2.0 (the "License");
	 you may not use this file except in compliance with the License.
	 You may obtain a copy of the License at

		 http://www.apache.org/licenses/LICENSE-2.0

	 Unless required by applicable law or agreed to in writing, software
	 distributed under the License is distributed on an "AS IS" BASIS,
	 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	 See the License for the specific language governing permissions and
	 limitations under the License.
 */

package com.pituruh.tjroute;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.GradientDrawable.Orientation;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.RelativeLayout.LayoutParams;

import com.pituruh.utils.NavigationDataSet;
import com.pituruh.utils.NavigationSaxHandler;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.OverlayItem;
import com.pituruh.utils.FindRouteSitesList;
import com.pituruh.utils.FindRouteXMLHandler;
import com.pituruh.utils.MyOverLay;
import com.pituruh.utils.RouteResultList;
import com.pituruh.utils.ShelterXMLHandler;
import com.pituruh.utils.ShelterSitesList;
import com.pituruh.views.BaloonLayout;
import com.pituruh.views.RouteOverlay;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

public class RouteResultMap extends MapActivity implements Runnable {
	private MapView map = null;
	private MyLocationOverlay me = null;
	private BaloonLayout noteBaloon;
	/** Create Object For SiteList Class */
	ShelterSitesList sitesList = null;
	private String selectedShelter;
	/*private ProgressDialog pd;*/
	ProgressBar pb;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.map_find_route_result);

		/*		 Bundle extras = getIntent().getExtras();
	     selectedShelter = extras.getString("selectedShelter");*/

		map = (MapView) findViewById(R.id.map);
		Resources res = getResources();
		int colors[] = { res.getColor(R.color.actionbar_color_1),
				res.getColor(R.color.actionbar_color_2) };
		GradientDrawable grad = new GradientDrawable(Orientation.TOP_BOTTOM,
				colors);
		LinearLayout layout = (LinearLayout) findViewById(R.id.buttonlayout);
		layout.setBackgroundDrawable(grad);

		TextView title_bar = (TextView) findViewById(R.id.title_bar);
		title_bar.setText(R.string.pencarian_rute);

		map.getController().setZoom(17);
		map.setBuiltInZoomControls(true);
		me = new MyLocationOverlay(this, map);

        ImageButton btnShare = (ImageButton) findViewById(R.id.btn_share);
        btnShare.setVisibility(View.VISIBLE);
        ImageView imgSeparator = (ImageView) findViewById(R.id.title_separator);
        imgSeparator.setVisibility(View.VISIBLE);
        
		/****progress dialog***/
/*		pd = ProgressDialog.show(this, getString(R.string.working), getString(R.string.loading_data_from_server), true,
				false);
*/		pb = (ProgressBar) findViewById(R.id.title_progress);
		pb.setVisibility(View.VISIBLE);
		Thread thread = new Thread(this);
		thread.start();

		/****end of progress dialog***/

	}

	public void run(){
		try {
			/** Handling XML */
			SAXParserFactory spf = SAXParserFactory.newInstance();
			SAXParser sp = spf.newSAXParser();
			XMLReader xr = sp.getXMLReader();

			/** Send URL to parse XML Tags */
			URL sourceUrl = new URL(
			"http://transjogja.only.web.id/app/xml/findroute.xml");


			/** Create handler to handle XML Tags ( extends DefaultHandler ) */
			FindRouteXMLHandler myXMLHandler = new FindRouteXMLHandler();
			xr.setContentHandler(myXMLHandler);
			xr.parse(new InputSource(sourceUrl.openStream()));

			/** Get result from MyXMLHandler SitlesList Object */
			FindRouteSitesList sitesList = FindRouteXMLHandler.sitesList;
			String[] startPoint = getCoordinate(sitesList.getRoutes().getCoordinate().get(0));
			for (int i = 0; i < sitesList.getRoutes().getName().size(); i++) {
				String[] endPoint = getCoordinate(sitesList.getRoutes().getCoordinate().get(i));

				GeoPoint srcGeoPoint = new GeoPoint((int) (new Double(startPoint[0]) * 1E6),
						(int) (new Double(startPoint[1]) * 1E6));
				GeoPoint destGeoPoint = new GeoPoint((int) (new Double(endPoint[0]) * 1E6),
						(int) (new Double(endPoint[1]) * 1E6));

				DrawPath(srcGeoPoint, destGeoPoint, Color.GREEN, map);

			}
			map.getController().animateTo(new GeoPoint((int)(Double.valueOf(startPoint[0]) * 1E6), 
					(int)(Double.valueOf(startPoint[1]) * 1E6)));

		} catch (Exception e) {
			System.out.println("XML Pasing Exception = " + e);
		}

		handler.sendEmptyMessage(0);
	}
	
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			/*pd.dismiss();*/
			pb.setVisibility(View.GONE);
			
			setupOverlay();
		}
	};
	
	private void setupOverlay(){
		CreateBaloon();		
	}
	
	@Override
	public void onStart() {
		super.onStart();
/*		try {
			*//** Handling XML *//*
			SAXParserFactory spf = SAXParserFactory.newInstance();
			SAXParser sp = spf.newSAXParser();
			XMLReader xr = sp.getXMLReader();

			*//** Send URL to parse XML Tags *//*
			URL sourceUrl = new URL(
			"http://transjogja.only.web.id/app/xml/findroute.xml");


			*//** Create handler to handle XML Tags ( extends DefaultHandler ) *//*
			FindRouteXMLHandler myXMLHandler = new FindRouteXMLHandler();
			xr.setContentHandler(myXMLHandler);
			xr.parse(new InputSource(sourceUrl.openStream()));

		} catch (Exception e) {
			System.out.println("XML Pasing Exception = " + e);
		}

		*//** Get result from MyXMLHandler SitlesList Object *//*
		FindRouteSitesList sitesList = FindRouteXMLHandler.sitesList;
		String[] startPoint = getCoordinate(sitesList.getRoutes().getCoordinate().get(0));
		for (int i = 0; i < sitesList.getRoutes().getName().size(); i++) {
			String[] endPoint = getCoordinate(sitesList.getRoutes().getCoordinate().get(i));

			GeoPoint srcGeoPoint = new GeoPoint((int) (new Double(startPoint[0]) * 1E6),
					(int) (new Double(startPoint[1]) * 1E6));
			GeoPoint destGeoPoint = new GeoPoint((int) (new Double(endPoint[0]) * 1E6),
					(int) (new Double(endPoint[1]) * 1E6));

			DrawPath(srcGeoPoint, destGeoPoint, Color.GREEN, map);

		}
*//*		map.getController().animateTo(new GeoPoint((int)(Double.valueOf(startPoint[0]) * 1E6), 
				(int)(Double.valueOf(startPoint[1]) * 1E6)));
*/
		/*		Drawable marker = getResources().getDrawable(R.drawable.marker);

		marker.setBounds(0, 0, marker.getIntrinsicWidth(), marker
				.getIntrinsicHeight());

		map.getOverlays().add(new SitesOverlay(marker));


		map.getOverlays().add(me);*/

		//drawPath(sitesList.getRoutes(), Color.parseColor("#add331"), map );

	}

	@Override
	public void onResume() {
		super.onResume();

		me.enableCompass();
	}

	@Override
	public void onPause() {
		super.onPause();

		me.disableCompass();
	}

	@Override
	protected boolean isRouteDisplayed() {
		return (false);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_S) {
			map.setSatellite(!map.isSatellite());
			return (true);
		} else if (keyCode == KeyEvent.KEYCODE_Z) {
			map.displayZoomControls(true);
			return (true);
		}

		return (super.onKeyDown(keyCode, event));
	}

	public void CreateBaloon() {
		LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		noteBaloon = (BaloonLayout) layoutInflater.inflate(R.layout.infobaloon,
				null);

		ImageButton btn_close = (ImageButton) noteBaloon.findViewById(R.id.btn_close);
		btn_close.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				map.removeView(noteBaloon);
				noteBaloon.setVisibility(View.GONE);
			}
		});


		RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

		layoutParams.addRule(RelativeLayout.CENTER_VERTICAL);
		layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
		noteBaloon.setLayoutParams(layoutParams);
	}

	private String[] getCoordinate(String coordinate) {
		return TextUtils.split(coordinate, ",");
	}

	private GeoPoint getPoint(double lat, double lon) {
		return (new GeoPoint((int) (lat * 1000000.0), (int) (lon * 1000000.0)));
	}

	public void onSaveClick(View v) {
		Intent intent = new Intent();

		Bundle extras = new Bundle();
		extras.putString("selectedShelter", selectedShelter);
		intent.putExtras(extras);
		setResult(RESULT_OK, intent);        
		finish();//Finish  current activity
	}

	private void DrawPath(GeoPoint src,GeoPoint dest, int color, MapView mMapView01)
	{
		// connect to map web service
		StringBuilder urlString = new StringBuilder();
		urlString.append("http://maps.google.com/maps?f=d&hl=en");
		urlString.append("&saddr=");//from
		urlString.append( Double.toString((double)src.getLatitudeE6()/1.0E6 ));
		urlString.append(",");
		urlString.append( Double.toString((double)src.getLongitudeE6()/1.0E6 ));
		urlString.append("&daddr=");//to
		urlString.append( Double.toString((double)dest.getLatitudeE6()/1.0E6 ));
		urlString.append(",");
		urlString.append( Double.toString((double)dest.getLongitudeE6()/1.0E6 ));
		urlString.append("&ie=UTF8&0&om=0&output=kml");
		Log.d("xxx","URL="+urlString.toString());
		// get the kml (XML) doc. And parse it to get the coordinates(direction route).
		Document doc = null;
		HttpURLConnection urlConnection= null;
		URL url = null;
		try
		{
			url = new URL(urlString.toString());
			urlConnection=(HttpURLConnection)url.openConnection();
			urlConnection.setRequestMethod("GET");
			urlConnection.setDoOutput(true);
			urlConnection.setDoInput(true);
			urlConnection.connect();

			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			doc = db.parse(urlConnection.getInputStream());

			if(doc.getElementsByTagName("GeometryCollection").getLength()>0)
			{
				//String path = doc.getElementsByTagName("GeometryCollection").item(0).getFirstChild().getFirstChild().getNodeName();
				String path = doc.getElementsByTagName("GeometryCollection").item(0).getFirstChild().getFirstChild().getFirstChild().getNodeValue() ;
				Log.d("xxx","path="+ path);
				String [] pairs = path.split(" ");
				String[] lngLat = pairs[0].split(","); // lngLat[0]=longitude lngLat[1]=latitude lngLat[2]=height
				// src
				GeoPoint startGP = new GeoPoint((int)(Double.parseDouble(lngLat[1])*1E6),(int)(Double.parseDouble(lngLat[0])*1E6));
				mMapView01.getOverlays().add(new MyOverLay(startGP,startGP,1));
				GeoPoint gp1;
				GeoPoint gp2 = startGP;
				for(int i=1;i<pairs.length;i++) // the last one would be crash
				{
					lngLat = pairs[i].split(",");
					gp1 = gp2;
					// watch out! For GeoPoint, first:latitude, second:longitude
					gp2 = new GeoPoint((int)(Double.parseDouble(lngLat[1])*1E6),(int)(Double.parseDouble(lngLat[0])*1E6));
					mMapView01.getOverlays().add(new MyOverLay(gp1,gp2,2,color));
					Log.d("xxx","pair:" + pairs[i]);
				}
				mMapView01.getOverlays().add(new MyOverLay(dest,dest, 3)); // use the default color
			}
		}
		catch (MalformedURLException e)
		{
			e.printStackTrace();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		catch (ParserConfigurationException e)
		{
			e.printStackTrace();
		}
		catch (SAXException e)
		{
			e.printStackTrace();
		}
	}

}